<script lang="ts" setup>
import { ref, watch } from 'vue';

import { IconifyIcon } from '@vben/icons';

import {
  Button,
  Col,
  Form,
  FormItem,
  Input,
  InputNumber,
  Row,
  Select,
  SelectOption,
  Switch,
} from 'ant-design-vue';

// Props
const props = defineProps<{
  capability?: any;
}>();

// Emits
const emit = defineEmits<{
  update: [data: any];
}>();

// 响应式数据
const formData = ref({
  states: [
    { name: '空闲', code: 'idle', description: '资源处于空闲状态' },
    { name: '已预订', code: 'reserved', description: '资源已被预订' },
    { name: '已占用', code: 'occupied', description: '资源正在被使用' },
  ],
  transitions: [
    {
      from: 'idle',
      to: 'reserved',
      trigger: 'reserve',
      condition: '',
      action: '',
    },
    {
      from: 'reserved',
      to: 'occupied',
      trigger: 'checkin',
      condition: '',
      action: '',
    },
    {
      from: 'occupied',
      to: 'idle',
      trigger: 'checkout',
      condition: '',
      action: '',
    },
  ],
  initialState: 'idle',
  enableStateMachine: true,
  allowSelfTransition: false,
  strictMode: true,
  autoValidate: true,
  keepHistory: true,
  historyLimit: 100,
});

// 监听props变化
watch(
  () => props.capability,
  (newCapability) => {
    if (newCapability?.stateMachine) {
      formData.value = {
        ...formData.value,
        ...newCapability.stateMachine,
      };
    }
  },
  { immediate: true },
);

// 方法
const handleFormChange = () => {
  emit('update', { stateMachine: formData.value });
};

const addState = () => {
  formData.value.states.push({
    name: '',
    code: '',
    description: '',
  });
  handleFormChange();
};

const removeState = (index: number) => {
  formData.value.states.splice(index, 1);
  handleFormChange();
};

const addTransition = () => {
  formData.value.transitions.push({
    from: '',
    to: '',
    trigger: '',
    condition: '',
    action: '',
  });
  handleFormChange();
};

const removeTransition = (index: number) => {
  formData.value.transitions.splice(index, 1);
  handleFormChange();
};
</script>

<template>
  <div class="capability-state-machine">
    <Form layout="vertical" :model="formData">
      <div class="state-machine-section">
        <h4>状态机配置</h4>
        <p class="section-desc">配置资源的状态转换规则</p>

        <!-- 状态定义 -->
        <div class="config-group">
          <h5>状态定义</h5>
          <div class="states-list">
            <div
              v-for="(state, index) in formData.states"
              :key="index"
              class="state-item"
            >
              <Row :gutter="16">
                <Col :span="6">
                  <Input
                    v-model:value="state.name"
                    placeholder="状态名称"
                    @change="handleFormChange"
                  />
                </Col>
                <Col :span="6">
                  <Input
                    v-model:value="state.code"
                    placeholder="状态代码"
                    @change="handleFormChange"
                  />
                </Col>
                <Col :span="8">
                  <Input
                    v-model:value="state.description"
                    placeholder="状态描述"
                    @change="handleFormChange"
                  />
                </Col>
                <Col :span="4">
                  <Button type="text" danger @click="removeState(index)">
                    删除
                  </Button>
                </Col>
              </Row>
            </div>
          </div>
          <Button
            type="dashed"
            @click="addState"
            style="width: 100%; margin-top: 16px"
          >
            <IconifyIcon icon="ant-design:plus-outlined" />
            添加状态
          </Button>
        </div>

        <!-- 状态转换 -->
        <div class="config-group">
          <h5>状态转换</h5>
          <div class="transitions-list">
            <div
              v-for="(transition, index) in formData.transitions"
              :key="index"
              class="transition-item"
            >
              <Row :gutter="16">
                <Col :span="5">
                  <Select
                    v-model:value="transition.from"
                    placeholder="起始状态"
                    @change="handleFormChange"
                  >
                    <SelectOption
                      v-for="state in formData.states"
                      :key="state.code"
                      :value="state.code"
                    >
                      {{ state.name }}
                    </SelectOption>
                  </Select>
                </Col>
                <Col :span="2" style=" line-height: 32px;text-align: center">
                  <IconifyIcon icon="ant-design:arrow-right-outlined" />
                </Col>
                <Col :span="5">
                  <Select
                    v-model:value="transition.to"
                    placeholder="目标状态"
                    @change="handleFormChange"
                  >
                    <SelectOption
                      v-for="state in formData.states"
                      :key="state.code"
                      :value="state.code"
                    >
                      {{ state.name }}
                    </SelectOption>
                  </Select>
                </Col>
                <Col :span="6">
                  <Input
                    v-model:value="transition.trigger"
                    placeholder="触发事件"
                    @change="handleFormChange"
                  />
                </Col>
                <Col :span="4">
                  <Button type="text" danger @click="removeTransition(index)">
                    删除
                  </Button>
                </Col>
              </Row>
              <Row :gutter="16" style="margin-top: 8px">
                <Col :span="12">
                  <Input
                    v-model:value="transition.condition"
                    placeholder="转换条件（可选）"
                    @change="handleFormChange"
                  />
                </Col>
                <Col :span="12">
                  <Input
                    v-model:value="transition.action"
                    placeholder="转换动作（可选）"
                    @change="handleFormChange"
                  />
                </Col>
              </Row>
            </div>
          </div>
          <Button
            type="dashed"
            @click="addTransition"
            style="width: 100%; margin-top: 16px"
          >
            <IconifyIcon icon="ant-design:plus-outlined" />
            添加转换
          </Button>
        </div>

        <!-- 初始状态 -->
        <div class="config-group">
          <h5>初始状态</h5>
          <Row :gutter="24">
            <Col :span="12">
              <FormItem label="默认状态" name="initialState">
                <Select
                  v-model:value="formData.initialState"
                  placeholder="请选择初始状态"
                  @change="handleFormChange"
                >
                  <SelectOption
                    v-for="state in formData.states"
                    :key="state.code"
                    :value="state.code"
                  >
                    {{ state.name }}
                  </SelectOption>
                </Select>
              </FormItem>
            </Col>
            <Col :span="12">
              <FormItem label="启用状态机" name="enableStateMachine">
                <Switch
                  v-model:checked="formData.enableStateMachine"
                  @change="handleFormChange"
                />
              </FormItem>
            </Col>
          </Row>
        </div>

        <!-- 状态验证 -->
        <div class="config-group">
          <h5>状态验证</h5>
          <Row :gutter="24">
            <Col :span="8">
              <FormItem label="允许自转换" name="allowSelfTransition">
                <Switch
                  v-model:checked="formData.allowSelfTransition"
                  @change="handleFormChange"
                />
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem label="严格模式" name="strictMode">
                <Switch
                  v-model:checked="formData.strictMode"
                  @change="handleFormChange"
                />
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem label="自动验证" name="autoValidate">
                <Switch
                  v-model:checked="formData.autoValidate"
                  @change="handleFormChange"
                />
              </FormItem>
            </Col>
          </Row>
        </div>

        <!-- 状态历史 -->
        <div class="config-group">
          <h5>状态历史</h5>
          <Row :gutter="24">
            <Col :span="12">
              <FormItem label="保留历史记录" name="keepHistory">
                <Switch
                  v-model:checked="formData.keepHistory"
                  @change="handleFormChange"
                />
              </FormItem>
            </Col>
            <Col :span="12">
              <FormItem label="历史记录数量" name="historyLimit">
                <InputNumber
                  v-model:value="formData.historyLimit"
                  :min="1"
                  :max="1000"
                  style="width: 100%"
                  @change="handleFormChange"
                />
              </FormItem>
            </Col>
          </Row>
        </div>
      </div>
    </Form>
  </div>
</template>

<style lang="less" scoped>
.capability-state-machine {
  padding: 24px;

  .state-machine-section {
    h4 {
      margin-bottom: 8px;
      color: #333;
      font-weight: 600;
    }

    .section-desc {
      margin-bottom: 24px;
      color: #666;
      font-size: 14px;
    }

    .config-group {
      margin-bottom: 32px;
      padding: 20px;
      border: 1px solid #f0f0f0;
      border-radius: 8px;
      background: #fafafa;

      h5 {
        margin-bottom: 16px;
        color: #333;
        font-weight: 600;
        font-size: 16px;
      }

      .states-list {
        .state-item {
          margin-bottom: 16px;
          padding: 16px;
          border: 1px solid #e8e8e8;
          border-radius: 6px;
          background: white;
        }
      }

      .transitions-list {
        .transition-item {
          margin-bottom: 16px;
          padding: 16px;
          border: 1px solid #e8e8e8;
          border-radius: 6px;
          background: white;
        }
      }
    }
  }
}
</style>
